import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { Message } from 'element-ui'
import Cookies from 'js-cookie'

var JsonaI = {}
console.log(Cookies.get('aI'))
if (Cookies.get('aI') !== undefined) {
  JsonaI = JSON.parse(Cookies.get('aI'))
}

const state = {
  token: getToken(),
  name: JsonaI.name || '',
  avatar: JsonaI.avatar || '',
  introduction: JsonaI.introduction || '',
  roles: JsonaI.roles || [],
  create_time: JsonaI.create_time || '',
  first_login: JsonaI.first_login || true
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_CREATETIME: (state, create_time) => {
    state.create_time = create_time
  },
  SET_FIRST_LOGIN: (state, first_login) => {
    state.first_login = first_login
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const token = response.data.data.token

        var { userName, userAvatar, userRole, introduction, createTime } = response.data.data.userInfo

        if (userRole === 2) {
          userRole = ['admin']
        }

        userAvatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
        introduction = '此账号为最高管理员账号'
        commit('SET_ROLES', userRole)
        commit('SET_NAME', userName)
        commit('SET_AVATAR', userAvatar)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_CREATETIME', createTime)

        commit('SET_TOKEN', token)

        var aI = {
          name: userName,
          avatar: userAvatar,
          introduction: introduction,
          roles: userRole,
          create_time: createTime,
          first_login: false
        }
        Cookies.set('aI', aI)
        setToken(token)
        Message({
          message: '登录成功',
          type: 'success',
          duration: 5 * 1000
        })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      try {
        const data = { 'roles': ['admin'] }
        // const data = { 'roles': ['admin'],
        //   'name': 'Admin',
        //   'avatar': 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        //   'introduction': '此账号为最高管理员账号',
        //   'create_time': '2023-05-03 08:14:25' }
        const { roles } = data

        commit('SET_ROLES', roles)

        // console.log('登录后', this.state.user)

        // console.log(state)
        resolve(data)
      } catch (error) {
        reject(error)
      }

      // getInfo(state.token).then(response => {
      //   const { data } = response

      //   if (!data) {
      //     // reject('Verification failed, please Login again.')
      //     reject('验证失败，请重新登录')
      //   }

      //   const { roles, name, avatar, introduction } = data

      //   // roles must be a non-empty array
      //   if (!roles || roles.length <= 0) {
      //     reject('getInfo: roles must be a non-null array!')
      //   }

      //   commit('SET_ROLES', roles)
      //   commit('SET_NAME', name)
      //   commit('SET_AVATAR', avatar)
      //   commit('SET_INTRODUCTION', introduction)
      //   resolve(data)
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      const userName = state.name
      logout({ 'userName': userName }).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        // resetRouter()
        Message({
          message: '退出成功',
          type: 'success',
          duration: 5 * 1000
        })
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },
  changeFirstLogin({ commit }, data) {
    commit('SET_FIRST_LOGIN', data)
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
